import { SettingsService, _HttpClient } from '@delon/theme';
import { Component, OnDestroy, Inject, Optional } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ITokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { StartupService } from '@core';
import { SessionService } from '@core/session.service';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
})
export class UserLoginComponent implements OnDestroy {

  constructor(
    fb: FormBuilder,
    modalSrv: NzModalService,
    private router: Router,
    private settingsService: SettingsService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private startupSrv: StartupService,
    public http: _HttpClient,
    public msg: NzMessageService,
    private _session: SessionService,
  ) {
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(4)]],
      password: [null, Validators.required],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [true],
    });
    modalSrv.closeAll();
  }

  // #region fields

  get userName() {
    return this.form.controls.userName;
  }

  get password() {
    return this.form.controls.password;
  }

  get mobile() {
    return this.form.controls.mobile;
  }

  get captcha() {
    return this.form.controls.captcha;
  }

  form: FormGroup;
  error = '';
  /**
   * 登录类型
   */
  loginType = 0;

  switch(ret: any) {
    this.loginType = ret.index;
  }

  /**
   * 获取验证码
   */
  getCaptcha() {
    if (this.mobile.invalid) {
      this.mobile.markAsDirty({onlySelf: true});
      this.mobile.updateValueAndValidity({onlySelf: true});
      return;
    }
    this.http.get('user-center/getRandomVerifyCode', {
      phone: this.mobile.value
    }).subscribe(_data => {
      this.msg.success('验证码：' + _data.element);
    });
  }

  // #endregion

  submit() {
    this.error = '';
    const params = {
      type: this.loginType,
    };
    if (this.loginType === 0) {
      this.userName.markAsDirty();
      this.userName.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      if (this.userName.invalid || this.password.invalid) {
        return;
      }
      Object.assign(params, {
        userNo: this.userName.value,
        password: this.password.value,
      });
    } else {
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mobile.invalid || this.captcha.invalid) {
        return;
      }
      Object.assign(params, {
        phone: this.mobile.value,
        captcha: this.captcha.value,
      })
    }

    // 默认配置中对所有HTTP请求都会强制 [校验](https://ng-alain.com/auth/getting-started) 用户 Token
    // 然一般来说登录请求不需要校验，因此可以在请求URL加上：`/login?_allow_anonymous=true` 表示不触发用户 Token 校验
    this.http
      .post('user-center/sysUserLogin', params).subscribe((_res) => {
      // 清空路由复用信息
      this.reuseTabService.clear();
      this._session.userNo = _res.element && _res.element.userNo;
      this._session.checkUserDetail().then(() => {
        this.router.navigateByUrl('/dashboard');
      }, (err) => {
        console.error('[登录异常 ===>]', err);
      });
    }, (err) => {
      this.error = err.body ? err.body.retMsg : '';
    });
  }

  ngOnDestroy(): void {
  }
}
